﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using static UnityEngine.UI.CanvasScaler;

public class ActionQueueUnitImage : MonoBehaviour, IPointerClickHandler
{
    public UnitBase Unit;
    RectTransform rectTransform;
    public Image UnitImage;
    public Text m_AtkText;
    public Text m_LifeText;
    Team Viewer;
    bool CanSee;

    public void SetUnit(UnitBase unit, Team Viewer)
    {
        Unit = unit;
        this.Viewer = Viewer;
        rectTransform = GetComponent<RectTransform>();
        RefreshSprite();
    }

    public void RefreshSprite()
    {
        if (Unit.team == Viewer || Unit.visible_to_opponent)
        {
            CanSee = true;
            Sprite unitSprite = ResourceManager<Sprite>.Instance.LoadResource($"unit_icons/{Unit.type.ToString()}_{Unit.team.ToString()}");
            UnitImage.sprite = unitSprite;

            m_AtkText.enabled = true;
            m_LifeText.enabled = true;
            m_AtkText.text = Mathf.Max(Unit.atk + Unit.atk_fix, 0).ToString();
            if (Unit.atk_fix < 0)
            {
                m_AtkText.color = Color.red;
            }
            else if (Unit.atk_fix == 0)
            {
                m_AtkText.color = Color.white;
            }
            else
            {
                m_AtkText.color = Color.green;
            }

            m_LifeText.text = Unit.life.ToString();
            if (Unit.life < Unit.max_life)
            {
                m_LifeText.color = Color.red;
            }
            else if (Unit.life == Unit.max_life)
            {
                m_LifeText.color = Color.white;
            }
            else
            {
                m_LifeText.color = Color.green;
            }
        }
        else
        {
            CanSee = false;
            m_AtkText.enabled = false;
            m_LifeText.enabled = false;
            Sprite unitSprite = ResourceManager<Sprite>.Instance.LoadResource("unit_icons/unknow");
            UnitImage.sprite = unitSprite;
        }

        
    }

    public void DestroySelf()
    {
        if (DisplayUtility.IsInScreen(rectTransform))
        {
            GetComponent<Animation>().Play("dequeue");
        }
        else
        {
            Destroy(gameObject);
        }
    }

    public void OnDequeueEnd()
    {
        Debug.Log("OnDequeueEnd");
        Destroy(gameObject);
    }

    public void OnPointerClick(PointerEventData eventData)
    {
        if (!CanSee) return;

        Transform cameraTrans = Camera.main.transform;
        cameraTrans.position = new Vector3(Unit.Pos.x, Unit.Pos.y, cameraTrans.position.z);
    }
}
